package org.winplus.serial;

import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;

import org.winplus.serial.utils.SerialPort;
import org.winplus.serial.utils.SerialPortFinder;

import android.content.SharedPreferences;

public class Application extends android.app.Application {
	public SerialPortFinder mSerialPortFinder = new SerialPortFinder();
    private SerialPort mSerialPort = null;

    public SerialPort getSerialPort(String path,int baudrate)
            throws SecurityException, IOException,InvalidParameterException {
        if (mSerialPort == null) {

//                int baudrate = 115200;
//                int baudrate = 9600;
//                String path = "/dev/ttymxc8";///dev/ttymxc2

            /* Check parameters */
            if ( (path.length() == 0) || (baudrate == -1)) {
                    throw new InvalidParameterException();
            }

            /* Open the serial port */
            mSerialPort = new SerialPort(new File(path), baudrate, 0);
            //save data
            SharedPreferences sp = getSharedPreferences("serialport", MODE_PRIVATE);
            sp.edit().putString("path",path).apply();
            sp.edit().putInt("baudrate",baudrate).apply();

        }
        return mSerialPort;
    }

    public void closeSerialPort() {
            if (mSerialPort != null) {
                    mSerialPort.close();
                    mSerialPort = null;
            }
    }
}
